using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Reflection;

using ClassBuilderWizard.Interfaces;

namespace ClassBuilderWizard
{
    internal class PluginHelper
    {
        public PluginHelper()
        {
        }

        public List<Plugin> GetAllPlugins(string pluginPath)
        {
            List<Plugin> results = new List<Plugin>();
            if (Directory.Exists(pluginPath))
            {
                foreach (string f in Directory.GetFiles(pluginPath))
                {
                    FileInfo fi = new FileInfo(f);

                    if (fi.Extension == ".dll")
                    {
                        try
                        {
                            Assembly asm = Assembly.LoadFile(f);
                            if (asm != null)
                            {
                                foreach (Type t in asm.GetTypes())
                                {
                                    //ignore abstract classes
                                    if (t.IsAbstract) continue;

                                    //does the class impliment the plugin interface?
                                    Type[] interfaces = t.GetInterfaces();
                                    foreach (Type iface in interfaces)
                                    {
                                        if (iface == typeof(IPlugin))
                                        {
                                            //the current type "t" is a plugin
                                            Plugin p = new Plugin(f, t);
                                            results.Add(p);
                                            break;
                                        }
                                    }
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            string error = string.Format("Error loading file {0}.\n{1}", f, ex.Message);
                            System.Windows.Forms.MessageBox.Show(error, "Error Loading Plug-in", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
                        }
                    }
                }
            }

            return results;
        }
    }
}
